import threading
import random
import time

# 生产者 消费者 Condition版本
g_money = 0
lock = threading.Condition()
g_time = 0


class Producer(threading.Thread):
    def run(self):
        global lock
        global g_money
        global g_time
        for _ in range(10):
            lock.acquire()
            money = random.randint(1000, 10000)
            g_money += money
            g_time += 1
            print("生产者", threading.current_thread().name, "挣了{}元,当余额{}".format(money, g_money))
            # time.sleep(1)
            lock.notify_all()
            lock.release()


class Customer(threading.Thread):
    def run(self):
        global g_money
        for _ in range(100):
            lock.acquire()
            money = random.randint(1000, 10000)
            while g_money < money:
                if g_time >= 50:
                    lock.release()
                    return
                print("================消费者", threading.current_thread().name,
                      "想花{}元，但余额不足,当前余额{}".format(money, g_money))
                lock.wait()
            g_money -= money
            print("================消费者", threading.current_thread().name, "花费了{}元,当前余额{}".format(money, g_money))
            # time.sleep(1)
            lock.release()


def start():
    for i in range(5):
        th = Producer(name='生产者{}'.format(i))
        th.start()
    for i in range(5):
        cust = Customer(name='消费者{}'.format(i))
        cust.start()


if __name__ == '__main__':
    start()
